import React from "react";
import {
  Form,
  Modal,
  Row,
  Col,
  Button,
  Checkbox,
  Card,
  Spin,
} from "antd";

import UsersTags from "components/usersTags/UsersTags";

import UserTree from "./UserTree";
import FlowHandleBaseForm from "./FlowHandleBaseForm";
import jiaqian from "../../assets/images/jiaqian.png";

import styles from "./TransferForm.less";

const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 },
};

// @Form.create()
class AddSignForm extends FlowHandleBaseForm {
  constructor(props) {
    super(props);
    

    this.checkedKeys = [];
    this.treeRef = "";
    this.state = {
      checkedNodes: [],
      disabled: false,
      noticeUserSelectorVisible: false,
      noticeUsers: [], // 自定添加的通知接收人  { userCode, userName, userOrgDesc },
      addCheckNodeToNoticeUser: false,
    };
  }

  componentDidMount() {
    /*
    const { dispatch, form } = this.props;
    dispatch({
      type: "FlowChart/getTemplateListByType",
      payload: {
        type: "TASK_ADDSIGNTASK",
      },
    }).then(({ errCode, datas }) => {
      if (errCode === 0 && datas.length > 0) {
        // console.log(datas[0]);
        form.setFieldsValue({
          title: datas[0].title,
          content: datas[0].content,
        });
        this.setState({ disabled: true });
      } else {
        this.setState({ disabled: false });
      }
    });
    */
    this.noticeKey = '加签';
    this.loadMessageTheme();
  }

  checkTree = (checkedKeys, checkedNodes) => {
    const u = sessionStorage.getItem("USER_CODE");
    if (checkedKeys.some(key => key === u)) {
      this.openNotificationWithIcon("error", "", "流程加签不可选择自己");
      return;
    }
    this.doCheckTree(checkedKeys, checkedNodes);
  };

  handleOk = () => {
    const {
      form,
      onCancel,
      dispatch,
      getList,
    } = this.props;
   
    const { noticeUsers } = this.state;
    const taskId = this.getTaskId();
    const applyUserId = this.getApplyUserId();
    const userCode = sessionStorage.getItem("USER_CODE");
    form.validateFields((err, values) => {
      if (err) {
        // 通知消息主题没有配置可以提交
        if (Object.keys(err).length > 1 || !err.messageThemName) {
          return;
        }
      }

      const { user, title, content } = values;

      const receiveMessagers = [];
      if (user.includes("publisher")) {
        receiveMessagers.push(applyUserId);
      }

      receiveMessagers.push(...noticeUsers.map(({ userCode: _code }) => _code));
      
      dispatch({
        type: "FlowHandle/addSignTask",
        payload: {
          taskId,
          title,
          content,
          userCode,
          signPersoneds: this.checkedKeys,
          receiveMessagers,
        },
      }).then(({ errCode, errMsg }) => {
        if (errCode === 0) {
          onCancel("addSignVisible", false);
          this.openNotificationWithIcon("success", "", "加签成功");
          if (getList instanceof Function) {
            getList();
          }
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      })
    });
  };

  render() {
    const { checkedNodes, disabled } = this.state;
    const { form, onCancel, visible, confirmLoading, dispatch } = this.props;
    const options = [
      { label: "发起人", value: "publisher" },
      // { label: "被加签人", value: "addSigner" },
    ];

    const { getFieldDecorator } = form;

    // 通知用户不显示左边选中的用户
    const customUsers = this.getCustomNoticeUsers();
    return (
      <Modal
        title="加签"
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => onCancel("addSignVisible", false)}
        width="650px"
        centered
        destroyOnClose
        className={styles.root}
        hideRequiredMark
        labelAlign="left"
        confirmLoading={confirmLoading}
        footer={[
          <Button key="back" onClick={() => onCancel("addSignVisible", false)}>
            取消
          </Button>,
          <Button
            key="ok"
            type="primary"
            onClick={this.handleOk}
            loading={confirmLoading}
          >
            确认加签
          </Button>,
        ]}
      >
        <Spin spinning={confirmLoading}>
          <Row>
            <Col span={12}>
              <div className={styles.select_box}>
                <div className={styles.user_list}>
                  {checkedNodes.map((item) => {
                    const { props } = item;
                    return (
                      <UsersTags
                        key={`${item.key}`}
                        label={props.title}
                        onClick={() => this.tagClose(item)}
                      />
                    );
                  })}
                </div>
                {checkedNodes.length > 0 && (
                  <span className={styles.clear} onClick={this.clearCheckNodes}>
                    清空
                  </span>
                )}
              </div>

              <div style={{ margin: "12px 0" }}>选择人员</div>
              <Row>
                <Card
                  size="small"
                  title="从组织中选择"
                  style={{ height: "100%", width: "100%" }}
                  bodyStyle={{ height: 305, overflow: "auto" }}
                >
                  <UserTree
                    getTreeRef={this.getTreeRef}
                    dispatch={dispatch}
                    checkTreefunction={this.checkTree}
                    checkedKeys={this.checkedKeys}
                  />
                </Card>
              </Row>
            </Col>
            <Col span={12}>
              <img src={jiaqian} alt="" className={styles.marginBo} />
              <Form {...formItemLayout}>
                {/*
                <div>
                  <div className={styles.formLabel}>消息标题：</div>
                  <Form.Item label="">
                    {getFieldDecorator("title", {
                      rules: [
                        { max: 100, message: "请不要超过100个字符" },
                        { required: true, message: "请输入消息标题" },
                      ],
                    })(<Input placeholder="请输入" disabled={disabled} />)}
                  </Form.Item>
                </div>
                <div>
                  <div className={styles.formLabel}>消息内容：</div>
                  <Form.Item label="">
                    {getFieldDecorator("content", {
                      rules: [
                        { max: 100, message: "请不要超过100个字符" },
                        { required: true, message: "请输入消息内容" },
                      ],
                    })(
                      <TextArea
                        placeholder="请输入消息内容"
                        rows={5}
                        disabled={disabled}
                      />,
                    )}
                  </Form.Item>
                </div>
                */}
                { this.renderNoticeTheme() }
                <div className={styles.last}>
                  <span>消息接收人：</span>
                  <Form.Item label="" {...formItemLayout}>
                    {this.renderNoticeUsers(
                      '被加签人', 
                      customUsers, 
                      getFieldDecorator("user", {
                        initialValue: ["publisher"] || null,
                        rules: [],
                      })(
                        <Checkbox.Group
                          options={options}
                          // defaultValue={["publisher"]}
                        />,
                      ),
                      disabled
                    )}
                  </Form.Item>
                </div>
              </Form>
            </Col>
          </Row>
        </Spin>
      </Modal>
    );
  }
}

export { AddSignForm as RawAddSignForm };
export default Form.create()(AddSignForm);
